package com.shgbit.tdd.args;

import lombok.AllArgsConstructor;

import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @author liuyong
 * @date 2020-04-07 18:13
 */
@AllArgsConstructor
public class Args {
    private final Command command;

    public Object get(String key) {
        Schemas schemas = command.getSchemas();
        String type = Optional.ofNullable(schemas.get(key)).orElseThrow(() -> new IllegalArgumentException("key不存在"));
        String value = command.get(key);
        switch (type) {
            case "bool": {
                return getBoolean(value);
            }
            case "int": {
                return getiInt(value);
            }
            case "str": {
                return value;
            }
            case "strings": {
                return getStrings(value);
            }
            case "ints": {
                return getInts(value);
            }
            default:
                return "不合法的key";
        }
    }

    private Object getBoolean(String value) {
        if (value == null) {
            return false;
        } else {
            value = value.toLowerCase();
            if ("true".equals(value)) {
                return true;
            } else if ("false".equals(value)) {
                return false;
            } else {
                return "不合法的value";
            }
        }
    }

    private List<Integer> getInts(String value) {
        return Arrays.stream(value.split(",")).map(Integer::parseInt).collect(Collectors.toList());
    }

    private List<String> getStrings(String value) {
        return Arrays.asList(value.split(","));
    }

    private Object getiInt(String value) {
        if (value == null) {
            return 0;
        }
        try {
            return Integer.parseInt(value);
        } catch (Exception e) {
            return "不合法的value";
        }
    }
}
